package com.wisely.highlight_spring4.ch2.el;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;

@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch2.el")
@PropertySource("classpath:com/wisely/highlight_spring4/ch2/el/test.properties")
public class ElConfig {
	@Value("test @Value set String")
	private String normal;
	
	@Value("#{systemProperties['os.name']}")  //注入操作系统属性
	private String osName;
	
	@Value("#{ T(java.lang.Math).random() * 100.0 }")  //注入表达式结果    value里面都用#{}来赋值。T(java.lang.Math)，它是指某个类，即Math这个类。
	private String randomNumber;
	
	@Value("#{demoService.auther}")  //注入其他类的属性
	private String fromAnother;
	
	@Value("classpath:com/wisely/highlight_spring4/ch2/el/test.txt")  //注入文件资源
	private Resource testFile;
	
	@Value("http://www.baidu.com") //注入网址资源
	private Resource testUrl;
	
	@Value("${book.name}")    //注入配置文件
	private String bookName;
	/**
	 * 注入properties可以从Environment中获得
	 */
	@Autowired
	private Environment environment; //注入配置文件
	/**
	 * 注入配置文件需要使用@PropertySource指定文件地址，若使用@Value注入，则需要配置PropertySourcesPlaceholderConfigurer的Bean
	 * 注意@Value("${book.name}") 使用的是"$"
	 * @return
	 */
	@Bean
	public static PropertySourcesPlaceholderConfigurer propertyConfiguer(){
		return new PropertySourcesPlaceholderConfigurer();
	}
	
	public void outputResource(){
		try {
			System.out.println(normal);
			System.out.println(osName);
			System.out.println(randomNumber);
			System.out.println(fromAnother);
			
			System.out.println(IOUtils.toString(testFile.getInputStream()));
			System.out.println(IOUtils.toString(testUrl.getInputStream()));
			
			System.out.println(bookName);
			System.out.println(environment.getProperty("book.auther"));
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
